package tools

import config._
import org.apache.commons.io.FileUtils
import play.api.libs.json.Json
import utils.ExecCommand

import scala.jdk.CollectionConverters._
import scala.math.log10

object Volcano extends MyFile  {

  def Run(path: String) = {
    var state = 0
    var msg = "Volcano Success!"
    var vol  = ""
    try {
      val matrix = s"$path/matrix.txt"
      val group = s"$path/group.txt"
      val command1 = s"Rscript  ${Global.toolsPath}/t_test/t-test.R -i $matrix -g $group -o $path -p FALSE -ve FALSE -c fdr -ptn 0.05 -qtn 0.05"
      println(command1)
      val exec = new ExecCommand()
      exec.exect(Array(command1), path)

      if (exec.isSuccess) {
        val ttest = Seq("geneId", "mean1", "std1", "mean2", "std2", "logFc", "p", "fdr").mkString("\t") +: s"$path/t_test_results.xls".readLines.tail.filter(_.indexOf("NA") == -1)

        FileUtils.writeLines(s"$path/allResult.txt".toFile,ttest.asJava)

        val cmd  = s"python ${Global.toolsPath}/volcano.py"
        val exec2 = new ExecCommand()
        exec2.exect(Array(cmd), path)

        if(exec2.isSuccess){
         vol = s"$path/div2.txt".readFileToString

        }else{
          state = 1
          msg = exec2.getOutStr
        }
      }else{
        state = 1
        msg = exec.getOutStr
      }

    } catch {
      case e: Exception => state = 1; msg = e.toString
    }
    Json.obj("state" -> state, "msg" -> msg,"vol" -> vol)
  }

  //log10(x):10的多少次方等于x
  def log2(x: Double): Double = log10(x + 1) / log10(2.0)


}
